from django.shortcuts import render_to_response, get_object_or_404
from django.template.context import RequestContext
from ximport.models import UploadFile
from django import forms
#from asset.models import CST, MyConstants
from jrcmodel.models import CST, MyConstants
from django.http import HttpResponseRedirect
from tradinglist.models import TradinglistNorm
import csv
from django.contrib.auth.decorators import login_required
import urllib
import datetime

class CsvUploadForm(forms.Form):
    file = forms.FileField()

class MonthProfit:
    month = 0
    sum = 0.0

def parse_csv_to_trading_list(csv_file_name):
    
    # Pass list of tradings to template
    tlist = list()

    # Do NOT handle exception    
    fp = open(csv_file_name, "rb")
    csvReader = csv.reader(fp, delimiter = ",")
    
    trading = None
    first = True
    
    for row in csvReader:
        # Parse only good lines, not titles :)
        if len(row) > 5:
            if first:
                # Need to create TradinglistNorm object and fill with entry info
                trading = TradinglistNorm()
                trading.set_entry_type(row[1])
#                trading.entry_type = row[1]
#                trading.entry_date = row[2]
                trading.entry_date = datetime.datetime.strptime(row[2], "%Y-%m-%d %H:%M")
#                print "Entry date: %s" % trading.entry_date
                trading.entry_price = float(row[4])
                
                # Flag that entry info is filled, next line is exit
                first = False
                
            else:
                trading.set_exit_type(row[1])
#                trading.exit_type = row[1]
#                trading.exit_date = row[2]
                trading.exit_date = datetime.datetime.strptime(row[2], "%Y-%m-%d %H:%M")
                print "Exit date: %s" % trading.exit_date
                trading.exit_price = float(row[4])

#                print trading.get_month_nr()
                
                # Adds to list
                tlist.append(trading)

                # Flag that entry is finished, next line will be new
                first = True

    return tlist

@login_required
def import_csv_file(request, pk):
    f = get_object_or_404(UploadFile, pk = pk)
    
    tlist = list()
    # Delete previous import
    TradinglistNorm.objects.filter(csv_file_id__pk = pk).delete()

    inserted = 0

    try:
        tlist = parse_csv_to_trading_list(f.import_file.path)
        for t in tlist:
            t.csv_file_id = f
            print t
            t.save()
            inserted += 1
        
    except IOError:
        print "Not found CSV file: %s" % f.import_file.name
        return HttpResponseRedirect("/help/nofile/" + urllib.quote_plus(f.import_file.name))

    return render_to_response("ximport/import_csv_file.html", {"f": f, "inserted": inserted})

@login_required
def parse_csv_file(request, pk):
    f = get_object_or_404(UploadFile, pk = pk)
    
    tlist = list()

    try:
        tlist = parse_csv_to_trading_list(f.import_file.path)
    except IOError:
        print "Not found CSV file: %s" % f.import_file.name
        return HttpResponseRedirect("/help/nofile/" + urllib.quote_plus(f.import_file.name))

#    # Pass list of tradings to template
#    tlist = list()
#    
#    trading = None
#    first = True
#    
#    for row in csvReader:
#        # Parse only good lines, not titles :)
#        if len(row) > 5:
#            if first:
#                # Need to create TradinglistNorm object and fill with entry info
#                trading = TradinglistNorm()
#                trading.entry_type = row[1]
#                trading.entry_date = row[2]
#                trading.entry_price = row[4]
#                
#                # Flag that entry info is filled, next line is exit
#                first = False
#                
#            else:
#                trading.exit_type = row[1]
#                trading.exit_date = row[2]
#                trading.exit_price = row[4]
#
#                print trading.get_month_nr()
#                
#                # Adds to list
#                tlist.append(trading)
#
#                # Flag that entry is finished, next line will be new
#                first = True

    return render_to_response("ximport/parse_csv_file.html", {"f": f, "tlist": tlist}, context_instance = RequestContext(request) )

@login_required
def show_upload_file(request, pk):
    f = get_object_or_404(UploadFile, pk = pk)
    
    print "Opening CSV file: %s..." % f.import_file.path
    fp = open(f.import_file.path, "rb")
    reader = csv.reader(fp, delimiter = ",")
    
    return render_to_response("ximport/showuploadfile.html", {"reader": reader})

def draw_candle_chart(request):
    print "IDs: %s " % request.GET.get("ids")
    id = request.GET.get("ids")
#    upfile = UploadFile.objects.get(pk = request.GET.get("ids"))
    f = get_object_or_404(UploadFile, pk = id)
    print "Path: %s" % f.import_file.path
    
    fp = open(f.import_file.path, "rb")
    csvReader = csv.reader(fp, delimiter = ",")

    # Pass list of tradings to template
    tlist = list()
    
    trading = None
    first = True

    for row in csvReader:
        # Parse only good lines, not titles :)
        if len(row) > 5:
            if first:
                # Need to create TradinglistNorm object and fill with entry info
                trading = TradinglistNorm()
                trading.entry_type = row[1]
                trading.entry_date = row[2]
                trading.entry_price = row[4]
                
                # Flag that entry info is filled, next line is exit
                first = False
                
            else:
                trading.exit_type = row[1]
                trading.exit_date = row[2]
                trading.exit_price = row[4]
                
                # Adds to list
                tlist.append(trading)

                # Flag that entry is finished, next line will be new
                first = True 

    print "Total %d" % len(tlist)
    return render_to_response("ximport/draw_candle_chart.html", {"tlist": tlist})

def parse(request, id):
    #xml = UploadFile.objects.get(pk = id)
    
    if request.method == "POST":
        form = CsvUploadForm(request.POST, request.FILES)
        if form.is_valid():
            f = request.FILES['file']
            print f
            print f.name
            fp = open(f.name, "wb+")
            for chunk in f.chunks():
                fp.write(chunk)
            fp.close()
            
            up = UploadFile()
            up.status_id = 1
            up.import_file = f
            up.save()
            
            return HttpResponseRedirect("/test/%d/parse_csv" % up.pk)
    
    cst = get_object_or_404(CST, pk = id)
    #uf = get_object_or_404(UploadFile, pk = id)
    #print uf
    form = CsvUploadForm()
#    print form
    
    return render_to_response("ximport/parse.html", {"cst": cst, "form": form}, context_instance=RequestContext(request))
    
    
